package com.lm.resilience4j.service;

import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import org.springframework.stereotype.Service;
import java.util.Random;

@Service
public class ExternalApiService {

    private final Random random = new Random();

    @CircuitBreaker(name = "externalApiCB", fallbackMethod = "fallbackResponse")
    @Retry(name = "externalApiRetry")
    @RateLimiter(name = "apiRateLimiter")
    public String callExternalApi() {
        // 模拟外部API调用失败场景
        if (random.nextInt(100) < 70) {
            throw new RuntimeException("❌ External API call failed!");
        }
        return "✅ External API success response";
    }

    // 熔断/重试/限流失败时的回退方法
    public String fallbackResponse(Throwable throwable) {
        return "⚠️ Fallback: external API unavailable, please try later.";
    }
}